import java.util.Stack;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User: Administrator
 * Data: 2023 - 08 - 21
 * Time: 10:27
 */
//力扣20.有效的括号
class Solution1 {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();//栈只存放左括号
        for(int i = 0; i < s.length(); i++) {
            char c1 = s.charAt(i);
            if(c1 == '(' || c1 == '[' || c1 == '{') {
                stack.push(c1);
            }else {
                if(stack.isEmpty()) {//右括号比左括号多，包括字符串匹配但右括号比左括号多、字符串只有右括号
                    return false;
                }
                char c2 = stack.peek();
                if((c1 == ')' && c2 == '(') || (c1 == ']' && c2 == '[') || (c1 == '}' && c2 == '{')) {
                    stack.pop();
                }else {
                    return false;//字符串不匹配
                }
            }
        }
        if(!stack.isEmpty()) return false;//左括号比右括号多，包括字符串匹配但左括号比右括号多、字符串只有左括号
        return true;
    }
}
